import jwt, { JwtPayload } from 'jsonwebtoken'

const JWT_ACCESS_SECRET = process.env.JWT_ACCESS_SECRET || 'smart-home'
const JWT_REFRESH_SECRET = process.env.JWT_REFRESH_SECRET || 'smart-home'

const ACCESS_TOKEN_EXPIRES = process.env.JWT_ACCESS_TOKEN_EXPIRES || '1h'
const REFRESH_TOKEN_EXPIRES = process.env.JWT_REFRESH_TOKEN_EXPIRES || '7d'

// 生成 Access Token    
export function generateAccessToken(payload: JwtPayload): string {
    return jwt.sign(Object.assign(payload), JWT_ACCESS_SECRET, { expiresIn: ACCESS_TOKEN_EXPIRES })
}

// 生成 Refresh Token
export function generateRefreshToken(payload: JwtPayload): string {
    return jwt.sign(Object.assign(payload), JWT_REFRESH_SECRET, { expiresIn: REFRESH_TOKEN_EXPIRES })
}

// 验证 Access Token
export function verifyAccessToken(token: string): JwtPayload {
    try {
        return jwt.verify(token, JWT_ACCESS_SECRET) as JwtPayload
    } catch (error) {
        throw unauthorizedResponse("access_token无效")
    }
}

// 验证 Refresh Token
export function verifyRefreshToken(token: string): JwtPayload {
    try {
        return jwt.verify(token, JWT_REFRESH_SECRET) as JwtPayload
    } catch (error) {
        throw unauthorizedResponse("refresh_token无效")
    }
}

// 从请求头获取 Token
export function getTokenFromHeader(event): string | null {
    const authHeader = getHeader(event, 'authorization')
    if (!authHeader) return null

    const [type, token] = authHeader.split(' ')
    return type === 'Bearer' ? token : null
}
